// src/services/apiClient.ts
import axios, { AxiosInstance, InternalAxiosRequestConfig, AxiosError } from 'axios';
import { ApiResponse } from '../types/api.types';

// 创建API客户端实例
const createApiClient = (): AxiosInstance => {
  const apiClient = axios.create({
    baseURL: process.env.REACT_APP_API_BASE_URL || 'http://localhost:5000',
    timeout: 10000,
    headers: {
      'Content-Type': 'application/json',
    },
  });
  
  // 请求拦截器
  apiClient.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
      // 从 localStorage 获取 token
      const token = localStorage.getItem('token');
      if (token && config.headers) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      return config;
    },
    (error: AxiosError) => {
      return Promise.reject(error);
    }
  );
  
  // 响应拦截器
  apiClient.interceptors.response.use(
    (response) => {
      return response;
    },
    (error: AxiosError) => {
      // 处理 401 未授权错误
      if (error.response?.status === 401) {
        // 清除本地存储的 token
        localStorage.removeItem('token');
        // 如果不在登录页，则跳转到登录页
        if (window.location.pathname !== '/login') {
          window.location.href = '/login';
        }
      }
      
      // 处理其他错误
      if (error.response) {
        // 服务器返回了错误响应
        const message = (error.response.data as any)?.message || error.message;
        console.error('API Error:', message);
      } else if (error.request) {
        // 请求已发送但没有收到响应
        console.error('Network Error:', '请检查网络连接');
      } else {
        // 其他错误
        console.error('Error:', error.message);
      }
      
      return Promise.reject(error);
    }
  );
  
  return apiClient;
};

export const apiClient = createApiClient();

// 封装常用请求方法
export const apiRequest = {
  get: <T = any>(url: string, config?: any) => 
    apiClient.get<ApiResponse<T>>(url, config).then(res => res.data),
  
  post: <T = any>(url: string, data?: any, config?: any) => 
    apiClient.post<ApiResponse<T>>(url, data, config).then(res => res.data),
  
  put: <T = any>(url: string, data?: any, config?: any) => 
    apiClient.put<ApiResponse<T>>(url, data, config).then(res => res.data),
  
  delete: <T = any>(url: string, config?: any) => 
    apiClient.delete<ApiResponse<T>>(url, config).then(res => res.data),
  
  patch: <T = any>(url: string, data?: any, config?: any) => 
    apiClient.patch<ApiResponse<T>>(url, data, config).then(res => res.data),
};